import Cache from "../../utils/Cache";
import {
	TOKEN_NAME,
	BACK_PAGE_KEY,
	LOGIN_PAGE_PATH
} from "../../config/index";
import {
	useUserStore
} from "../../store/index";

/**
 * 检查是否登录
 * @return 
 */ 
export function checkLogin(): string | null {
	const token = Cache.getCache(TOKEN_NAME);
	if(!token) {
		const userStore = useUserStore();
		userStore.logout();
	}
	return token
}

/**
 * 去登录页面
 * @return 
 */ 
export function toLogin() {
	const prePageURL = getPrePage();
	Cache.setCache(
		BACK_PAGE_KEY,
		prePageURL,
		-1
	)
	
	uni.reLaunch({
		url: LOGIN_PAGE_PATH
	})
}

/**
 * 获取当前页面的路由信息
 * @return 
 */ 
export function getPrePage() {
	const pages = getCurrentPages();
	const lastPage = pages[pages.length - 1];
	let queryStr = "";
	if(lastPage['options']) {
			const options = lastPage.options;
			Object.keys(options).forEach((key, index) => {
				if(index === 0) queryStr += "?";
				queryStr += (key + "=" + options[key]);
			})
	}
	
	return lastPage.route + queryStr;
}